<template>
  <view class="math-formula">
    <!-- Formula Name -->
    <view v-if="formulaName" class="formula-name">{{ formulaName }}</view>

    <!-- New structured rendering with questionParts -->
    <view v-if="filteredQuestionParts && filteredQuestionParts.length" class="formula-structured">
      <view
          v-for="(part, index) in filteredQuestionParts"
          :key="index"
          :class="getPartClass(part)"
      >
        {{ typeof part === 'string' ? part : part.value }}
      </view>
    </view>

    <!-- Fallback to old format if questionParts not provided -->
    <view v-else-if="expression" class="formula-expression">
      <text class="formula-text">{{ textBeforeFormula }}</text>
      <text v-if="formulaPart" class="formula-math">{{ formulaPart }}</text>
      <text v-if="showQuestion" class="formula-text">= ?</text>
    </view>

    <!-- LaTeX rendering as supplement -->
    <view v-if="latexFormula && renderedLatex" class="latex-container" v-html="renderedLatex"></view>
  </view>
</template>

<script>
export default {
  name: 'MathFormula',
  props: {
    formulaName: {
      type: String,
      default: ''
    },
    expression: {
      type: String,
      default: ''
    },
    latexFormula: {
      type: String,
      default: ''
    },
    questionParts: {
      type: Array,
      default: () => []
    },
    substitutedFormula: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageLoaded: false,
      imageHeight: 'auto',
      katexReady: false,
      renderedLatex: ''
    }
  },
  mounted() {
    this.waitForKatex();
  },
  watch: {
    latexFormula() {
      this.$nextTick(() => {
        this.renderLatex();
      });
    }
  },
  computed: {
    // Filter parts to exclude formula/substituted when LaTeX is available
    filteredQuestionParts() {
      if (!this.questionParts || !this.questionParts.length) return [];
      if (!this.latexFormula) return this.questionParts;

      // If LaTeX is available, filter out the parts after formula
      const formulaIndex = this.questionParts.findIndex(part => part.type === 'formula')
      if (formulaIndex !== -1) {
        return this.questionParts.slice(0, formulaIndex + 1);
      }
    },
    textBeforeFormula() {
      if (!this.expression) return '';
      const trimmedExpr = this.expression.trim();
      const endsWithQuestion = trimmedExpr.endsWith('= ?');
      const exprWithoutQuestion = endsWithQuestion
          ? trimmedExpr.substring(0, trimmedExpr.length - 3).trim()
          : trimmedExpr;

      const hasMathOperators = /[*+\-/(\^).]/.test(exprWithoutQuestion);

      if (hasMathOperators) {
        return '';
      }

      const lastEqualsIndex = exprWithoutQuestion.lastIndexOf('=');
      if (lastEqualsIndex === -1) return this.expression;

      const beforeEquals = exprWithoutQuestion.substring(0, lastEqualsIndex).trim();
      const afterEquals = exprWithoutQuestion.substring(lastEqualsIndex + 1).trim();

      const hasMathOps = /[*+\-/(\^)]/.test(afterEquals);

      if (hasMathOps) {
        return beforeEquals + '=';
      }
      return this.expression;
    },
    formulaPart() {
      if (!this.expression) return '';
      const trimmedExpr = this.expression.trim();
      const endsWithQuestion = trimmedExpr.endsWith('= ?');
      const exprWithoutQuestion = endsWithQuestion
          ? trimmedExpr.substring(0, trimmedExpr.length - 3).trim()
          : trimmedExpr;

      const hasMathOperators = /[*+\-/(\^).]/.test(exprWithoutQuestion);

      if (hasMathOperators) {
        return exprWithoutQuestion;
      }

      const lastEqualsIndex = exprWithoutQuestion.lastIndexOf('=');
      if (lastEqualsIndex === -1) return '';

      const afterEquals = exprWithoutQuestion.substring(lastEqualsIndex + 1).trim();

      const hasMathOps = /[*+\-/(\^)]/.test(afterEquals);

      if (hasMathOps) {
        return afterEquals;
      }
      return '';
    },
    showQuestion() {
      return this.expression && this.expression.trim().endsWith('= ?');
    }
  },
  methods: {
    waitForKatex() {
      let attempts = 0;
      const maxAttempts = 50; // Wait up to 5 seconds

      const checkKatex = () => {
        if (typeof katex !== 'undefined') {
          this.katexReady = true;
          this.renderLatex();
        } else if (attempts < maxAttempts) {
          attempts++;
          setTimeout(checkKatex, 100);
        } else {
          console.warn('KaTeX not loaded after timeout');
        }
      };

      checkKatex();
    },
    renderLatex() {
      // Check if KaTeX is available
      if (!this.katexReady || typeof katex === 'undefined' || !this.latexFormula) {
        return;
      }

      try {
        // Use renderToString instead of render for UniApp compatibility
        this.renderedLatex = katex.renderToString(this.latexFormula, {
          throwOnError: false,
          displayMode: false // Use inline mode for better layout
        });
      } catch (error) {
        console.error('KaTeX rendering error:', error);
        this.renderedLatex = '';
      }
    },
    getPartClass(part) {
      if (typeof part === 'string') {
        return 'part-text';
      }
      if (part.type === 'value') {
        return 'part-value';
      }
      if (part.type === 'formula') {
        return 'part-formula';
      }
      if (part.type === 'substituted') {
        return 'part-substituted';
      }
      return 'part-text';
    }
  }
}
</script>

<style lang="scss" scoped>
.math-formula {
  width: 100%;
  text-align: center;
  padding: 20rpx;

  .formula-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #8a2be2;
    margin-bottom: 20rpx;
    display: block;
    background: linear-gradient(135deg, #8a2be2, #9370db);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-shadow: 0 2rpx 4rpx rgba(138, 43, 226, 0.2);
  }

  .formula-structured {
    font-size: 28rpx;
    line-height: 1.8;
    padding: 30rpx 20rpx;
    text-align: left;

    .part-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      display: inline;
    }

    .part-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #007AFF;
      padding: 4rpx 12rpx;
      margin: 0 2rpx;
      display: inline-block;
    }

    .part-formula {
      font-size: 36rpx;
      font-weight: bold;
      color: #8a2be2;
      font-family: 'Times New Roman', 'Georgia', serif;
      padding: 8rpx 16rpx;
      margin: 0 8rpx;
      display: inline-block;
      letter-spacing: 0.05em;
    }

    .part-substituted {
      font-size: 32rpx;
      font-weight: bold;
      color: #ff6b35;
      background-color: #ffede6;
      border: 1rpx solid rgba(255, 107, 53, 0.5);
      border-radius: 10rpx;
      font-family: 'Courier New', 'Monaco', monospace;
      padding: 6rpx 14rpx;
      margin: 0 4rpx;
      display: inline-block;
      letter-spacing: 0.02em;
    }
  }

  .formula-expression {
    font-size: 32rpx;
    color: #333;
    font-family: 'Georgia', 'Times New Roman', serif;
    line-height: 1.8;
    padding: 30rpx 20rpx;
    word-break: break-word;
    text-align: left;

    letter-spacing: 0.03em;
    font-variant-numeric: tabular-nums;

    .formula-text {
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
    }

    .formula-math {
      display: inline-block;
      font-size: 40rpx;
      font-weight: bold;
      color: #8a2be2;
      font-family: 'Times New Roman', 'Georgia', serif;
      padding: 12rpx 18rpx;
      margin: 0 8rpx;
      letter-spacing: 0.05em;
    }
  }

  .latex-container {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow-x: auto;
    font-size: 40rpx;
  }
}
</style>

